package com.hanxiaozhang.threadbase1ndedition.no1synchronizedkeyword;

/**
 * 〈一句话功能简述〉<br>
 * 〈非线程安全举例〉
 * <p>
 * 非线程安全下的打印顺序：
 * a set over!
 * b set over!
 * b num = 200
 * a num = 200
 * <p>
 * 线程安全下的打印顺序（使用synchronized关键字）：
 * a set over!
 * a num = 100
 * b set over!
 * b num = 200
 *
 * @author hanxinghua
 * @create 2021/11/9
 * @since 1.0.0
 */
public class No1NonThreadSafe {

    /**
     * 共享变量
     */
    private  int num = 0;

    public   /*synchronized*/   void add(String username) {
        try {
            if ("a".equals(username)) {
                num = 100;
                System.out.println("a set over!");
                Thread.sleep(2000);
            } else {
                num = 200;
                System.out.println("b set over!");
            }
            System.out.println(username + " num = " + num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {

        No1NonThreadSafe example = new No1NonThreadSafe();

        new Thread(() -> {
            example.add("a");
        }, "THREAD-1").start();
        new Thread(() -> {
            example.add("b");
        }, "THREAD-1").start();

    }
}
